const axios = require('axios');
const redis = require('../config/redis');
const cheerio = require('cheerio');

class BaiduService {
  constructor() {
    this.baseURL = process.env.BAIDU_HOTSEARCH_URL || 'https://top.baidu.com/api/board';
    this.timeout = parseInt(process.env.REQUEST_TIMEOUT) || 10000;
  }

  // 获取百度热搜数据
  async getHotSearch() {
    const cacheKey = 'baidu:hotsearch';
    
    return redis.getOrSet(cacheKey, async () => {
      try {
        console.log('Fetching fresh Baidu hot search data...');
        
        // 尝试使用百度API接口
        const response = await axios.get(this.baseURL, {
          timeout: this.timeout,
          headers: {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'Accept': 'application/json, text/plain, */*',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
            'Referer': 'https://top.baidu.com/',
            'Origin': 'https://top.baidu.com'
          }
        });

        if (response.data && response.data.data) {
          return this.transformData(response.data);
        } else {
          // 如果API返回的不是预期格式，尝试备用方法
          return await this.tryAlternativeMethod();
        }
      } catch (error) {
        console.error('Baidu API Error:', error.message);
        // 返回模拟数据作为降级方案
        return this.generateMockData();
      }
    }, parseInt(process.env.CACHE_DURATION) || 300);
  }

  // 备用方法：尝试其他获取方式
  async tryAlternativeMethod() {
    try {
      // 尝试移动端API
      const mobileResponse = await axios.get('https://top.baidu.com/mobile', {
        headers: {
          'User-Agent': 'Mozilla/5.0 (Linux; Android 10; Mobile) AppleWebKit/537.36'
        }
      });
      
      // 这里可以添加移动端HTML解析逻辑
      console.log('Trying mobile alternative...');
      return this.generateMockData();
    } catch (error) {
      console.log('Mobile alternative failed, using mock data');
      return this.generateMockData();
    }
  }

  // 转换百度数据格式
  transformData(data) {
    if (!data || !data.data || !data.data.cards || data.data.cards.length === 0) {
      console.log('No valid data found in Baidu API response');
      return this.generateMockData();
    }

    const hotspots = [];
    let rank = 1;
    
    // 遍历所有卡片
    for (const card of data.data.cards) {
      if (card && card.content && Array.isArray(card.content)) {
        for (const item of card.content) {
          if (item && (item.word || item.query || item.title)) {
            const title = item.word || item.query || item.title || `百度热搜 ${rank}`;
            const heatValue = item.hotScore || item.indexHot || (1000000 - rank * 30000);
            const desc = item.desc || item.description || '百度热搜';
            
            hotspots.push({
              id: `baidu_${rank}_${Date.now()}`,
              title: title,
              description: desc,
              platform: '百度',
              views: this.formatHeat(heatValue),
              comments: Math.round(heatValue / 100),
              heat: this.calculateHeat(heatValue),
              trend: this.calculateTrend(),
              updatedAt: new Date().toISOString(),
              url: item.url || `https://www.baidu.com/s?wd=${encodeURIComponent(title)}`,
              tags: item.label ? [item.label] : ['热门'],
              rank: rank,
              isAd: item.isCommercial || item.isAd || false,
              note: heatValue ? `${heatValue} 热度` : ''
            });
            
            rank++;
            if (rank > 30) break;
          }
        }
      }
      if (rank > 30) break;
    }

    return hotspots.length > 0 ? hotspots : this.generateMockData();
  }

  // 格式化热度显示
  formatHeat(score) {
    if (score >= 1000000) {
      return `${(score / 1000000).toFixed(1)} 万热度`;
    } else if (score >= 1000) {
      return `${(score / 1000).toFixed(1)} 千热度`;
    }
    return `${score} 热度`;
  }

  // 计算热度值
  calculateHeat(score) {
    const maxScore = 10000000; // 百度热度通常很高
    const heat = Math.min(100, Math.round((score / maxScore) * 100));
    return Math.max(heat, 10);
  }

  // 计算趋势
  calculateTrend() {
    return Math.floor(Math.random() * 10) - 5;
  }

  // 生成模拟数据（降级方案）
  generateMockData() {
    console.log('Generating mock Baidu hot search data...');
    
    const mockTopics = [
      {
        id: 'baidu_1',
        title: '最新电影资讯',
        description: '456 万热度',
        platform: '百度',
        views: '456 万热度',
        comments: 4560,
        heat: 95,
        trend: 8,
        updatedAt: new Date().toISOString(),
        url: 'https://top.baidu.com/',
        tags: ['影视', '热门'],
        rank: 1,
        isAd: false,
        note: '456 万热度'
      },
      {
        id: 'baidu_2',
        title: '科技新闻',
        description: '378 万热度',
        platform: '百度',
        views: '378 万热度',
        comments: 3780,
        heat: 88,
        trend: 5,
        updatedAt: new Date().toISOString(),
        url: 'https://top.baidu.com/',
        tags: ['科技', '热门'],
        rank: 2,
        isAd: false,
        note: '378 万热度'
      },
      {
        id: 'baidu_3',
        title: '体育赛事',
        description: '295 万热度',
        platform: '百度',
        views: '295 万热度',
        comments: 2950,
        heat: 82,
        trend: 3,
        updatedAt: new Date().toISOString(),
        url: 'https://top.baidu.com/',
        tags: ['体育', '热门'],
        rank: 3,
        isAd: false,
        note: '295 万热度'
      },
      {
        id: 'baidu_4',
        title: '健康养生',
        description: '234 万热度',
        platform: '百度',
        views: '234 万热度',
        comments: 2340,
        heat: 76,
        trend: -2,
        updatedAt: new Date().toISOString(),
        url: 'https://top.baidu.com/',
        tags: ['健康', '热门'],
        rank: 4,
        isAd: false,
        note: '234 万热度'
      },
      {
        id: 'baidu_5',
        title: '教育资讯',
        description: '187 万热度',
        platform: '百度',
        views: '187 万热度',
        comments: 1870,
        heat: 71,
        trend: -4,
        updatedAt: new Date().toISOString(),
        url: 'https://top.baidu.com/',
        tags: ['教育', '热门'],
        rank: 5,
        isAd: false,
        note: '187 万热度'
      }
    ];

    return mockTopics;
  }

  // 获取单个热点详情
  async getHotspotDetail(id) {
    const allData = await this.getHotSearch();
    const hotspot = allData.find(item => item.id === id);
    
    if (!hotspot) {
      throw new Error('热点不存在');
    }

    // 生成模拟趋势数据
    const trendData = this.generateTrendData(hotspot.heat);
    
    return {
      hotspot,
      trendData
    };
  }

  // 生成趋势数据
  generateTrendData(baseHeat) {
    const now = new Date();
    const data = [];
    
    for (let i = 11; i >= 0; i--) {
      const time = new Date(now.getTime() - i * 2 * 60 * 60 * 1000);
      const hour = time.getHours().toString().padStart(2, '0');
      const minute = '00';
      
      // 模拟热度波动
      const fluctuation = Math.random() * 10 - 5;
      const heat = Math.max(10, Math.min(100, baseHeat + fluctuation));
      
      data.push({
        time: `${hour}:${minute}`,
        heat: Math.round(heat)
      });
    }
    
    return data;
  }
}

module.exports = new BaiduService();